package com.sxdz.config

import com.alibaba.druid.pool.DruidDataSource
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.apache.ibatis.session.SqlSessionFactory
import org.mybatis.spring.SqlSessionFactoryBean
import org.mybatis.spring.annotation.MapperScan
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.PropertySource
import org.springframework.context.annotation.PropertySources
import org.springframework.core.env.Environment
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.jdbc.datasource.DataSourceTransactionManager

import javax.sql.DataSource

/**
 * Created by zb on 2015/6/10.
 */
@CompileStatic
@TypeChecked
@Configuration
@PropertySource("classpath:db.properties")
/*@PropertySources(@PropertySource("classpath:db.properties"))*/
@MapperScan(basePackages="com.sxdz.controller.mapper")
class DataSourceConfig {

    @Autowired
    private Environment env

    @Bean
    DataSource dataSource() {
        new DruidDataSource(
                url:env.getProperty("mysql.url"),
                username : env.getProperty("mysql.username"),
                password : env.getProperty("mysql.password"),

                maxActive : env.getProperty("mysql.maxActive") as int,
                initialSize : 0,
                minIdle : 0,
                maxWait : 60000l,
                validationQuery : "SELECT 1",
                testOnBorrow : false,
                testOnReturn : false,
                testWhileIdle : true,
                timeBetweenEvictionRunsMillis : 60000l,
                minEvictableIdleTimeMillis : 25200000l,
                removeAbandoned : true,
                removeAbandonedTimeout : 1800,
                logAbandoned : true
        )
    }

    @Bean
    DataSourceTransactionManager transactionManager() {
        new DataSourceTransactionManager(dataSource())
    }

    @Bean
    SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(
                dataSource: dataSource,
                mapperLocations:new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml")
        )
        return sessionFactory.getObject()
    }
}
